<?php
class Application_Model_CommitMapper
{
	protected $_dbTable;
	
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Commit');
		}
		return $this->_dbTable;
	}

	public function save(Application_Model_Commit $commit)
	{
		$data = array(
			'blog_id'       => $commit->getBlogId(),
			'parent_id'     => $commit->getParentId(),
            'commit_content'=> $commit->getContent(),
            'from'          => $commit->getFrom(),
		);
		
		return $this->getDbTable()->insert($data);
	}

	public function findByBlogId($blogId)
    {
        $select = $this->getDbTable()->select()
            ->where('blog_id = ?', $blogId)
            ->order('create_tm DESC');
        $result = $this->getDbTable()->fetchAll($select)->toArray();
		if (0 == count($result)) {
			return;
		}
        $entries   = array(0=>null);
        $abc =array();
        $this->recu($result, $entries);
        return $entries;
	}
	
    public function fetchAll()
    {
        $resultBlog = $this->getDbTable()->fetchAll();
        $entries   = array();
        foreach ($resultBlog as $row) {
            $entry = new Application_Model_Blog();
            $entry->setId($row->id)
                  ->setKeyword($row->keyword);
            $entries[] = $entry;
        }
        return $entries;
    }
//Recursion
    public function recu(&$result, &$array) {
        if ( null === $result ) {
            return $array;
        } 
        foreach ($result as $key => $row) {
            if (array_key_exists( $row['parent_id'], $array)) {
                $entry = new Application_Model_Commit();
                $entry->setBlogId($row['blog_id'])
                      ->setContent($row['commit_content'])
                      ->setFrom($row['from'])
                      ->setCreateDt($row['create_tm'])
                      ->setParentId($row['parent_id'])
                      ->setId($row['id']);
                $array[$row['parent_id']][$row['id']][] = $entry;
                array_splice($result, $key, 1);
                $this->recu($result, $array[$row['parent_id']]);
                reset($result);
            } 
            
        }
    }
}
